package com.jf.cloud.service.sysmanager.common.util;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Properties;

/**
 * 属性文件读取工具类
 * 
 * @author 程伟平 2012-3-12
 */
public final class PropertiesUtil {
	
	/**
	 * 日志
	 */
	private static Log log = LogFactory.getLog(PropertiesUtil.class);

	/**
	 * 全局配置数据
	 */
	private static final Properties GLOBAL_DATA = load("global.properties");

	/**
	 * 获取全局配置数据
	 * 
	 * @return 全局配置数据
	 */
	public static Properties getGlobalData() {
		return GLOBAL_DATA;
	}

	/**
	 * 加载属性文件
	 * 
	 * @author 程伟平 2012-3-12
	 * @param propsFileName 属性文件名称
	 * @return 属性文件
	 * @throws IOException IO异常
	 */
	public static Properties load(String propsFileName) {
		Properties props = new Properties();
		try {
//			ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
//			props.load(classLoader.getResourceAsStream(propsFileName));
		} catch (Exception e) {
			log.error("加载属性文件【 " + propsFileName + "】失败！", e);
		}
		return props;
	}
	
	/**
	 * 刷新属性文件内容
	 * 
	 * @author 姚龙 2014-07-07
	 * @param systemProps 属性内容
	 */
	public static void refresh(List<Map<String, Object>> systemProps) {
		Properties props = getGlobalData();
		if (systemProps != null && !systemProps.isEmpty()) {
			for (Map<String, Object> data : systemProps) {
				props.put(data.get("CFG_KEY"), data.get("CFG_VALUE"));
			}
		}
	}
	
	/**
	 * 刷新属性文件内容
	 * 
	 * @author 姚龙 2014-07-07
	 * @param systemProps 属性内容
	 */
	public static void refresh(Map<String, Object> systemProps) {
		Properties props = getGlobalData();
		if (systemProps != null && !systemProps.isEmpty()) {
			props.putAll(systemProps);
		}
	}
	
	/**
	 * 获取全局的值
	 * @param key
	 * @return str value if null return ""
	 * @author i3yx@qq.com
	 */
	public static String getValue(String key){
		String rs = "";
		if(GLOBAL_DATA!=null && GLOBAL_DATA.containsKey(key)){ 
			rs = GLOBAL_DATA.getProperty(key, ""); 
		}
		return rs;
	} 
	
	public static String getValue(String key, String defaultVal){
		String rs = "";
		if(GLOBAL_DATA!=null && GLOBAL_DATA.containsKey(key)){ 
			rs = GLOBAL_DATA.getProperty(key, defaultVal); 
		}
		return rs;
	}
}
